<template>
  <el-form
    :model="ruleForm"
    status-icon
    :rules="rules"
    ref="ruleForm"
    label-width="100px"
    class="demo-ruleForm"
  >
    <el-form-item label="旧密码" prop="oldPass" required="">
      <el-input type="password" v-model="ruleForm.oldPass"></el-input>
    </el-form-item>
    <el-form-item label="新密码" prop="newPass" required="">
      <el-input type="password" v-model="ruleForm.newPass"></el-input>
    </el-form-item>
    <el-form-item label="确定新密码" prop="checkNewPass" required="">
      <el-input type="password" v-model="ruleForm.checkNewPass"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">确定修改</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import {changePass} from '@/api/user'
import { error, success } from "@/utils";
export default {
  data() {
    let validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入旧密码"));
      } else {
        callback();
      }
    };

    let validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入新密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkNewPass");
        }
        callback();
      }
    };

    let validatePass3 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入新密码"));
      } else if (value !== this.ruleForm.newPass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        oldPass: "",
        newPass: "",
        checkNewPass: "",
      },
      rules: {
        oldPass: [{ validator: validatePass, trigger: "blur" }],
        newPass: [{ validator: validatePass2, trigger: "blur" }],
        checkNewPass: [{ validator: validatePass3, trigger: "blur" }],
      },
    };
  },
  methods: {
    async submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
            const res = await changePass(this.ruleForm.oldPass, this.ruleForm.newPass)
            if (res.code === 1) {
                success('修改密码成功')
                this.$emit('close')
            } else {
                error(res.msg)
            }
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style></style>
